// pages/wage/wage.js
const app = getApp()

Page({
  data: {
    wageData: [],
    totalQuantity: 0,
    totalWage: 0,
    averageWage: 0,
    selectedMonth: '',
    startDate: '',
    endDate: '',
    loading: true,
    refreshing: false
  },

  onLoad() {
    // 设置默认日期范围为当月
    const now = new Date()
    const startDate = new Date(now.getFullYear(), now.getMonth(), 1)
    const endDate = new Date()
    const selectedMonth = `${now.getFullYear()}年${String(now.getMonth() + 1).padStart(2, '0')}月`
    
    this.setData({
      startDate: this.formatDate(startDate),
      endDate: this.formatDate(endDate),
      selectedMonth: selectedMonth
    })
    
    this.loadWageStats()
  },

  onShow() {
    this.loadWageStats()
  },

  onPullDownRefresh() {
    this.setData({
      refreshing: true
    })
    this.loadWageStats().then(() => {
      wx.stopPullDownRefresh()
      this.setData({
        refreshing: false
      })
    })
  },

  // 格式化日期
  formatDate(date) {
    const year = date.getFullYear()
    const month = String(date.getMonth() + 1).padStart(2, '0')
    const day = String(date.getDate()).padStart(2, '0')
    return `${year}-${month}-${day}`
  },

  // 开始日期变化
  onStartDateChange(e) {
    this.setData({
      startDate: e.detail.value
    })
    this.loadWageStats()
  },

  // 结束日期变化
  onEndDateChange(e) {
    this.setData({
      endDate: e.detail.value
    })
    this.loadWageStats()
  },

  // 显示月份选择器
  showDatePicker() {
    const now = new Date()
    const currentYear = now.getFullYear()
    const currentMonth = now.getMonth()
    
    // 生成月份选项（最近12个月）
    const months = []
    for (let i = 11; i >= 0; i--) {
      const date = new Date(currentYear, currentMonth - i, 1)
      const year = date.getFullYear()
      const month = date.getMonth()
      months.push({
        label: `${year}年${String(month + 1).padStart(2, '0')}月`,
        value: `${year}-${String(month + 1).padStart(2, '0')}`
      })
    }
    
    wx.showActionSheet({
      itemList: months.map(item => item.label),
      success: (res) => {
        const selected = months[res.tapIndex]
        const [year, month] = selected.value.split('-')
        const startDate = new Date(parseInt(year), parseInt(month) - 1, 1)
        const endDate = new Date(parseInt(year), parseInt(month), 0) // 当月最后一天
        
        this.setData({
          selectedMonth: selected.label,
          startDate: this.formatDate(startDate),
          endDate: this.formatDate(endDate)
        })
        
        this.loadWageStats()
      }
    })
  },

  // 刷新工资统计
  refreshWage() {
    this.setData({
      loading: true
    })
    this.loadWageStats()
  },

  // 加载工资统计
  loadWageStats() {
    return app.request({
      url: '/getWageStats',
      data: {
        start_date: this.data.startDate,
        end_date: this.data.endDate
      }
    }).then((res) => {
      const wageData = res.data.reports || []
      
      // 计算统计数据
      let totalQuantity = 0
      let totalWage = 0
      let averageWage = 0
      
      wageData.forEach(item => {
        totalQuantity += parseInt(item.quantity) || 0
        totalWage += parseFloat(item.wage) || 0
      })
      
      // 计算平均单价
      if (totalQuantity > 0) {
        averageWage = (totalWage / totalQuantity).toFixed(2)
      }
      
      this.setData({
        wageData: wageData,
        totalQuantity: totalQuantity,
        totalWage: totalWage,
        averageWage: averageWage,
        loading: false
      })
    }).catch((err) => {
      console.error('获取工资统计失败:', err)
      this.setData({
        loading: false
      })
      wx.showToast({
        title: '获取统计失败',
        icon: 'none'
      })
    })
  },

  // 查看记录详情
  viewRecord(e) {
    const record = e.currentTarget.dataset.record
    wx.showModal({
      title: '报工详情',
      content: `订单号：${record.order_no}\n产品：${record.product_name} - ${record.model_name}\n工序：${record.process_name}\n数量：${record.quantity}\n工资：¥${record.wage}\n时间：${record.createtime_text}`,
      showCancel: false
    })
  }
}) 